package com.olap.starter.common.service.online;

import com.alibaba.fastjson.JSONObject;
import com.olap.starter.common.service.cache.TableCacheService;
import com.olap.starter.common.service.cache.TableConfigCaCheService;
import com.olap.starter.common.service.cache.TableMainCaCheService;
import com.olap.starter.core.exception.OnlineException;
import com.olap.starter.core.response.Result;
import com.olap.starter.core.response.ResultUtil;
import com.olap.starter.pojo.TableConfig;
import com.olap.starter.pojo.TableMain;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.olap.starter.common.util.AESCRUDUtils.encryptWithCompress;

@Service
@Log4j2
public class OnlineServices {

    @Autowired
    private TableConfigCaCheService tableConfigCaCheService;
    @Autowired
    private TableCacheService tableCacheService;
    @Autowired
    private TableMainCaCheService tableMainCaCheService;

    public Result refreshCache() {
        tableConfigCaCheService.init();
        tableCacheService.init();
        tableMainCaCheService.init();
        return ResultUtil.success("刷新成功！");
    }


    public Map<String, Object> init(long uuid, String theme) {
        long start = System.currentTimeMillis();
        TableConfig tableConfig = tableConfigCaCheService.getTableConfig(uuid, theme);
        long init = System.currentTimeMillis();
        Map<String, Object> data = tableCacheService.getData(tableConfig);
        long end = System.currentTimeMillis();
        log.info("==>\tinit[" + (init - start) + "ms]\tdata[" + (end - init) + "]\tsum[" + (end - start) + "ms]");
        return data;
    }


    public Map<String, Object> init(long uuid) {
        long start = System.currentTimeMillis();
        TableMain tableMain = tableMainCaCheService.getTableMain(uuid);
        if (tableMain == null) {
            throw new OnlineException("无表格uuid[" + uuid + "]");
        }
        Map<String, Object> mapResp = new HashMap<>();
        mapResp.put("theme", tableMain.getTheme());
        mapResp.put("searchRow", tableMain.getSearchRow());
        mapResp.put("treeUuid", tableMain.getTreeUuid());
        long initTableMain = System.currentTimeMillis();
        List<TableConfig> tableConfigs = tableConfigCaCheService.getTableConfig(uuid);
        long initTableConfig = System.currentTimeMillis();
        for (TableConfig tableConfig : tableConfigs) {
            Map<String, Object> mapConfig = tableCacheService.getData(tableConfig);
            mapResp.put(tableConfig.getTheme(), mapConfig);
        }
        long end = System.currentTimeMillis();
        log.info("==>\tinitTableMain[" + (initTableMain - start) + "ms]\tinitTableConfig[" + (initTableConfig - initTableMain) + "]\ttableConfigs[" + (end - initTableConfig) + "]\tsum[" + (end - start) + "ms]");
        return mapResp;
    }
}
